<script setup lang="ts">
import { request } from '@/api';
import b64toBlob from 'b64-to-blob';
import { showToast, type ActionSheetAction } from 'vant';
import { ref, onMounted } from 'vue';

// 1. 修改头像
// 1.1 控制修改头像弹层的显示/隐藏
const showAvatarSheet = ref(false)
// 1.2 打开相册/相机
const onSelectAvatar = async (item: ActionSheetAction, index: number) => {
    if (index === 0) {
        // console.log('拍照')
        const res = await mk.pickerCamera()
    }
    else if (index === 1) {
        try {
            // console.log('相册')
            const res = await mk.pickerPhoto()
            // console.log('相册:', res)
            // base64 转 二进制
            const img = b64toBlob(res, 'image/jpeg')
            showAvatarSheet.value = false
            // 创建一个 转载数据的 FormData 对象
            const fd = new FormData()
            // 追加数据
            // file key
            // img 数据
            // 参数3 名字
            fd.append('file', img, Date.now() + '.jpeg')
            // 调用上传接口，根据接口文档设置地址和方法，FormData 设置到参数 2 即可
            // 上传完毕之后，用户的头像就更新了
            const uploadRes = await request.post<MkResponse<{ avatar: string }>>(
                'member/profile/avatar',
                fd
            )
            // 修改页面的显示
            profile.value.avatar = uploadRes.data.result.avatar
            // 获取 保存在 鸿蒙缓存中 用户信息
            const user = mk.queryUser()
            // 修改用户信息的头像 为上传成功之后的头像
            user.avatar = uploadRes.data.result.avatar
            // 更新鸿蒙端的头像
            mk.updateUser(user)
            showToast({ message: '上传成功' })
        } catch (error) {
            showToast({ message: '上传失败' })
        }
    }
}

// 生日选择弹层

const showBirthDayPop = ref(false)
const currentDate = ref(['2024', '09', '27'])
const minDate = new Date(1970, 1, 1)
const maxDate = new Date(2025, 1, 1)
const onChangeBirthday = () => {
    profile.value.birthday = currentDate.value.join("-")
    // console.log(UserBirthday);

    showBirthDayPop.value = false
}

// 省市区弹层
const areaList = ref<AreaColumns>({} as AreaColumns)
const showAreaPop = ref(false)
const selectArea = ref('')
onMounted(async () => {
    const res = await mk.getAreaColumns()
    areaList.value = res
})
const onAreaConfirm = ({ selectedValues, selectedOptions, selectedIndexes }) => {
    showAreaPop.value = false
    const area = selectedOptions.map(v => v.text)
    profile.value.fullLocation = area.join(' ')
    profile.value.provinceCode = selectedValues[0]
    profile.value.cityCode = selectedValues[1]
    profile.value.countryCode = selectedValues[2]
}

// 4. 职业选择弹层
const columns = [
    { text: '软件工程师', value: '软件工程师' },
    { text: '医生', value: '医生' },
    { text: '教师', value: '教师' },
    { text: '律师', value: '律师' },
    { text: '会计师', value: '会计师' },
    { text: '销售经理', value: '销售经理' },
    { text: '市场营销专员', value: '市场营销专员' },
    { text: '建筑师', value: '建筑师' },
    { text: '护士', value: '护士' },
    { text: '机械工程师', value: '机械工程师' }
]
const showProfessionPopup = ref(false)
const onChangeProfession = (data: { selectedValues: string[] }) => {

    profile.value.profession = data.selectedValues.join()
    showProfessionPopup.value = false
}

const profile = ref<ProfileInfo>({} as ProfileInfo)
onMounted(async () => {
    const res = await request.get<MkResponse<ProfileInfo>>('member/profile')
    // console.log(res.data.result);
    profile.value = res.data.result
})

const onSubmit = async () => {
    const res = await request.put<MkResponse<ProfileInfo>>('/member/profile', profile.value)
    mk.updateUser(res.data.result)
    showToast("更新成功")
}

</script>

<template>
    <div class="profile-edit-page">
        <!-- 头像部分 -->
        <div class="avatar">
            <van-image round width="100" height="100" class="avatar-img" :src="profile.avatar"
                @click="showAvatarSheet = true">
            </van-image>
            <div class="avatar-btn">
                <span @click="showAvatarSheet = true">修改头像</span>
            </div>
        </div>
        <van-action-sheet v-model:show="showAvatarSheet" :actions="[{ name: '拍照' }, { name: '相册' }]"
            @select="onSelectAvatar" cancel-text="取消" :style="{ paddingBottom: '20px' }"></van-action-sheet>
        <!-- 中间表单部分 -->
        <van-cell-group>
            <van-field v-model="profile.account" label="账号" readonly></van-field>
            <van-field v-model="profile.nickname" label="昵称" placeholder="请输入昵称"></van-field>
            <van-cell title="性别" class="gender">
                <van-radio-group v-model="profile.gender" :icon-size="16">
                    <van-radio name="男">男</van-radio>
                    <van-radio name="女">女</van-radio>
                    <van-radio name="未知">未知</van-radio>
                </van-radio-group>
            </van-cell>
            <van-field v-model="profile.birthday" label="生日" readonly placeholder="请选择日期"
                @click="showBirthDayPop = true"></van-field>
            <van-field v-model="profile.fullLocation" @click="showAreaPop = true" label="所在地" readonly
                placeholder="请选择所在地"></van-field>
            <van-field v-model="profile.profession" label="职业" readonly placeholder="请选择职业"
                @click="showProfessionPopup = true"></van-field>
        </van-cell-group>

        <div class="submit">
            <van-button round block type="primary" @click="onSubmit">
                保存资料
            </van-button>
        </div>
        <!-- 生日弹层 日期选择器弹窗 -->
        <van-popup v-model:show="showBirthDayPop" position="bottom">
            <van-date-picker v-model="currentDate" title="选择日期" :min-date="minDate" :max-date="maxDate"
                @confirm="onChangeBirthday" @cancle="showBirthDayPop = false" />
        </van-popup>
        <!-- 省市区弹层 -->
        <van-popup v-model:show="showAreaPop" position="bottom">
            <van-area v-model="selectArea" :area-list="areaList" title="选择省市区" @confirm="onAreaConfirm"
                @cancel="showAreaPop = false" />
        </van-popup>
        <!-- 选择职业弹层 -->
        <van-popup v-model:show="showProfessionPopup" round position="bottom">
            <van-picker :columns="columns" @confirm="onChangeProfession" @cancel="showProfessionPopup = false" />
        </van-popup>
    </div>
</template>

<style lang="css" scoped>
.avatar {
    padding: 30px;
    text-align: center;
    background-color: var(--mk-white);
}

.avatar-img {
    box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
    color: var(--mk-linear_end);
    margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
    width: 100px;
    flex: none;
}

.van-radio-group {
    display: flex;
    justify-content: space-between;
    height: 36px;
    width: 180px;
}

.submit {
    padding: 16px;
}
</style>